import 'dart:async';
import 'dart:io';

import 'package:bot_toast/bot_toast.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter/physics.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:get/get.dart';
import 'package:moonplay/common/common_style.dart';
import 'package:moonplay/common/event_bus_utils.dart';
import 'package:moonplay/locale/language.dart';
import 'package:moonplay/provide/provide.dart';
import 'package:moonplay/widgets/custom_footer.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'routes/app_pages.dart';

void main() {
  var userInfo = UserInfo();
  var themeProvider = ThemeProvider();
  var appSize = FontSizeProvide();
  var videoSetting = VideoSettingProvide();
  var providers = Providers();

  providers..provide(Provider<UserInfo>.value(userInfo));
  providers..provide(Provider<ThemeProvider>.value(themeProvider));
  providers..provide(Provider<FontSizeProvide>.value(appSize));
  providers..provide(Provider<VideoSettingProvide>.value(videoSetting));

  runApp(ProviderNode(
    child: MyApp(),
    providers: providers,
  ));
  if (Platform.isAndroid) {
    // 以下两行 设置android状态栏为透明的沉浸。写在组件渲染之后，是为了在渲染后进行set赋值，覆盖状态栏，写在渲染之前MaterialApp组件会覆盖掉这个值。
    SystemUiOverlayStyle systemUiOverlayStyle = SystemUiOverlayStyle(statusBarColor: Colors.transparent);
    SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
  }
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  /// 当前语言环境
  Locale gCurrentSupportLocale = Locale('zh', 'CH');
  StreamSubscription _eventSwitchLanguage;
  

  @override
  void initState() {
    super.initState();

    //控制设备为竖屏
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
    ]);

    
    _initAsync();

    //监听切换语言(1=中文简体 2=英文 3=繁體中文(香港))
    _eventSwitchLanguage = eventBus.on<SwitchLanguage>().listen((event) {
      var _data = event.language;
      print('当前选择的语言是: ${_data}');
      setState(() {
        gCurrentSupportLocale = _data;
      });
    });
  }

  
  /**
   * 初始化一些需要的东西
   */
  _initAsync() async {
    // App启动时读取Sp数据，需要异步等待Sp初始化完成。
    await SpUtil.getInstance();

    // SpUtil.remove('AppTheme');
    //判断缓存里面是否有设置主题色，如果有则取缓存里面的颜色(或者也可以称之为日间和夜间模式)
    var appTheme = SpUtil.getString('AppTheme');
    if(appTheme != null){
      ThemeMode _themes = appTheme == "Dark" ? ThemeMode.dark : ThemeMode.light;
      Provide.value<ThemeProvider>(context).setTheme(_themes);
    }

    // SpUtil.remove('storageAppSize');
    //判断缓存里面是否有设置app字体大小，如果有则取缓存里面的
    var storageAppSize = SpUtil.getDouble('storageAppSize');
    if(storageAppSize != null){
      Provide.value<FontSizeProvide>(context).initAppSize();
    }


    //读取缓存中的语言设置，如果有则取缓存中对应的语言
    int _idx = SpUtil.getInt('appLocal');
    if(_idx == 0) {
      //当缓存里面没有的时候它的值也是为0，这里需要注意，所以当为0的时候我们取手机的系统语言
      var _nowLocale = (WidgetsBinding.instance.window.locale).toString().substring(0, 2);
      // print("当前系统语言为:${_nowLocale}");
      if(_nowLocale == 'zh') {
        setState(() {
          gCurrentSupportLocale = Locale('zh', 'CH');
        });
      } else if(_nowLocale == 'en') {
        setState(() {
          gCurrentSupportLocale = Locale('en', 'US');
        });
      }
    } else {
      setState(() {
        // gCurrentSupportLocale = _idx;
      });
    }
  }
  
  @override
  Widget build(BuildContext context) {
    CommonStyle.ctx = context; // 注入context
    //初始化屏幕适配
    setDesignWHD(750.0, 1334.0, density: 2);
    ///全局配置下拉刷新设置
    return RefreshConfiguration(
      footerTriggerDistance: 100,         //距离底部边缘触发加载更多的距离
      dragSpeedRatio: 0.8,
      headerTriggerDistance: 80.0,        // 头部触发刷新的越界距离
      maxOverScrollExtent:100, //头部最大可以拖动的范围,如果发生冲出视图范围区域,请设置这个属性
      // maxUnderScrollExtent: 20, // 底部最大可以拖动的范围
      headerBuilder: () => MaterialClassicHeader(),
      ///自定义底部指示器
      footerBuilder: () => CustomFooter(
        height: 40,
        builder: buildCustomFooter
      ),
      enableLoadingWhenNoData: false,
      springDescription: SpringDescription(stiffness: 170, damping: 16, mass: 1.9),         // 自定义回弹动画,三个属性值意义请查询flutter api
      enableLoadingWhenFailed : true, //在加载失败的状态下,用户仍然可以通过手势上拉来触发加载更多
      hideFooterWhenNotFull: true, // Viewport不满一屏时,禁用上拉加载更多功能
      enableBallisticLoad: true, // 可以通过惯性滑动触发加载更多
      shouldFooterFollowWhenNotFull: (state) {
        // If you want load more with noMoreData state ,may be you should return false
        return false;
      },
      autoLoad: true,
      child: BotToastInit(
        child: Provide<ThemeProvider>(
          builder: (context, child, provider) {
            return GetMaterialApp(
              debugShowCheckedModeBanner: false,    //去掉debug图标
              enableLog: true,
              initialRoute: AppPages.INITIAL,
              getPages: AppPages.routes,
              opaqueRoute: false,
              popGesture: true,
              transitionDuration: Duration(milliseconds: 200),
              navigatorObservers: [
                BotToastNavigatorObserver()
              ],
              theme: provider.getTheme(),
              darkTheme: provider.getTheme(isDarkMode: true),
              themeMode: provider.getThemeMode(),
              localizationsDelegates: [
                ///初始化默认的 Material 组件本地化
                GlobalMaterialLocalizations.delegate,
                ///初始化默认的 通用 Widget 组件本地化
                GlobalWidgetsLocalizations.delegate,
                ///初始化自定义多语言环境运行
                MyLocalizationsDelegates.delegate,
              ],
              ///当前区域，如果为null则使用系统区域一般用于语言切换
              ///传入两个参数，语言代码，国家代码
              ///这里配制为中国
              locale: gCurrentSupportLocale,

              ///传入支持的语种数组
              supportedLocales: [
                const Locale('zh', 'CH'), // 中文，后面的countryCode暂时不指定
                const Locale('en', 'US'), // English 英文
                const Locale('zh', 'HK'), // 香港繁体字
              ],

              ///当传入的是不支持的语种，可以根据这个回调，返回相近,并且支持的语种
              localeResolutionCallback: (local, support) {
                ///当前软件支行的语言 也就是[supportedLocales] 中配制的语种
                if (support.contains(local)) {
                  return local;
                }
                ///如果当前软件运行的手机环境不在 [supportedLocales] 中配制的语种范围内
                ///返回一种默认的语言环境，这里使用的是中文
                return const Locale('zh', 'CH');
              },
            );
          }
        )
      ),
    );
  }
}


